﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text;
using System.Threading.Tasks;

namespace BunnyEater.Common.Jwt
{
    /// <summary>
    /// 通过nuget下载引用System.Net.Http.Formatting
    /// </summary>
    public static class HttpClientHelper
    {
        /// <summary>
        /// 发送Http请求
        /// </summary>
        /// <param name="httpType">请求类型：post、put、get、delete</param>
        /// <param name="actionName">方法名称</param>
        /// <param name="obj">对象参数</param>
        /// <returns></returns>
        public static T GetAll<T>(HttpType httpType, string actionName, string token, object obj = null)
        {
            HttpClient hc = new HttpClient();
            hc.BaseAddress = new Uri("http://localhost:61289/");
            hc.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("auth", token);
            hc.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            Task<HttpResponseMessage> task = null;
            switch (httpType)
            {
                case HttpType.HttpGet:
                    task = hc.GetAsync(actionName);
                    break;
                case HttpType.HttpPost:
                    task = hc.PostAsJsonAsync(actionName, obj);
                    break;
                case HttpType.HttpPut:
                    task = hc.PutAsJsonAsync(actionName, obj);
                    break;
                case HttpType.HttpDelete:
                    task = hc.DeleteAsync(actionName);
                    break;
            }
            task.Wait();
            if (task.Result.IsSuccessStatusCode)
            {
                var getresultstringTask = task.Result.Content.ReadAsStringAsync();
                getresultstringTask.Wait();
                var json = getresultstringTask.Result;
                return JsonConvert.DeserializeObject<T>(json);
            }
            return default;

            //if (result.IsSuccessStatusCode)
            //{
            //    var getresultstringTask = result.Content.ReadAsStringAsync();
            //    getresultstringTask.Wait();
            //    var json = getresultstringTask.Result;
            //    return json;
            //}
            //return string.Empty;
        }
    }
}
